param(
	#[string]$dmsWebUrl = "$(Read-Host 'Enter DMS Site Url [e.g. http://sites/dms]')",
	[string]$csvSource = "$(Read-Host 'Enter import csv file [e.g. c:\temp\source.csv]')",
	[string]$invoiceSourceFolder ="$(Read-Host 'Enter invoice source folder')",
	#[string]$invoiceWebUrl = "$(Read-Host 'Enter invoice web url [e.g. http://dms/sites/invoices]')",
	[string]$importYear =  "$(Read-Host 'Enter the invoice year [e.g. 2012]')"
)




#Load variables from configuration file
[System.Xml.XmlDocument] $xmlDoc = New-Object System.Xml.XmlDocument
$file = Resolve-Path (".\deployment.config")

if(!$file){
	Write-Host "Could not find the configuration file deployment.cnofig. Aborting." -ForegroundColor Red
	break
}

Write-Host "Parsing file: " $file
$xmlDoc = [xml](Get-Content $file)

$dmsWebUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.Url
$invoiceWebUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.InvoiceSite.Url

$searchService = $xmlDoc.Configuration.SearchService.Name
$scopeName =$xmlDoc.Configuration.SearchService.SearchScope.Name


		$spInvoiceListName = "Invoices"
		$spInvoicesDocumentLibraryName = "InvoiceDocuments"
		
		
		$documentType = "DocumentType"
		$documentName = "DocumentName"
		$customerName = "CustomerName"
		$customerNumber = "CustomerNumber"	
		$invoiceGUID = "InvoiceGUID"
		$invoiceType = "InvoiceType"
		$branchName = "BranchName" 
		$goodGuid= "GoodGUID" 
		$auctionID= "AuctionID" 
		$invoiceDate= "InvoiceDate" 
		$invoiceTotal= "InvoiceTotal" 
		$invoiceNumberSuffix= "InvoiceNumberSuffix" 
		$plateNumber= "PlateNumber" 
		$VIN= "VIN" 
		$consignmentVendorNumber= "ConsignmentVendorNumber" 
		$consignmentGoodNumber= "ConsignmentGoodNumber" 
		$goodID = "GoodID"
		$documentLink = "DocumentLink"

		#Year we are importing for
		
		if(!$invoiceSourceFolder.EndsWith('\'))
		{
			$invoiceSourceFolder = $invoiceSourceFolder + '\'
		}
		
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue		
		
Write-Host "`n===================`n# Starting Import #`n==================="


function getBranchNameID($branchName,$branchCode){
	$web = Get-SPWeb -identity $dmsWebUrl
	$branchList = $web.Lists['Branches'];
	$branches = $branchList.Items
	$branchID = 0;
	foreach($item in $branches){
		if($item["Title"] -eq $branchName)
		{
			$branchID = $item.ID
		}
	}
	if($branchID -eq 0){
		Write-Host "branch $branchName, which code is $branchCode doesn't exist in the list, insert to the list" -ForegroundColor Yellow
		$item = $branchList.AddItem();
		$item["Title"] = $branchName;
		$item["BranchCode"] = $branchCode;
		$item.update();
		$branchID = $item.ID;
		
		$web.Dispose();
	}
	else{
		$web.Dispose();	
	}
	
	return $branchID;
}


#Load the CSV file
#$csvSource = 'D:\Document Types\Invoices containing multiple sales\2012-05-21-11-10-20.csv'
$csvLength = @(Get-Content $csvSource).Length
$csv = Import-Csv $csvSource
Write-Host "CSV file loaded"

#Store the source folder
#$invoiceSourceFolder = 'D:\Document Types\Invoices containing multiple sales\'
#Write-Host "Source folder loaded"


if(!$invoiceWebUrl.EndsWith('/'))
{
	$invoiceWebUrl = $invoiceWebUrl + '/'
}

$invoiceYearWebUrl = $invoiceWebUrl + $importYear

#Load the site
$web = Get-SPWeb -identity $invoiceYearWebUrl #"http://turnersdms/invoices/2011/"
Write-Host "Site loaded"

$webRelativeUrl = $web.ServerRelativeUrl

#Load the document library
$listDocuments = $web.Lists[$spInvoicesDocumentLibraryName]
if(!$listDocuments){Write-Host 'list document is null' -ForegroundColor Red
	exit
}else{
	Write-Host 'list document loaded'-ForegroundColor Green
}
$listListItems = $web.Lists[$spInvoiceListName]

if(!$listListItems){Write-Host 'list document is null' -ForegroundColor Red 
	exit
}else{
	Write-Host 'invoice list is loaded'-ForegroundColor Green
}

$spFolder = $web.GetFolder($spInvoicesDocumentLibraryName)
$spFileCollection = $spFolder.Files
Write-Host "Document library loaded"

#Create folder
#Write-host "Creating initial folder"
#$currentFolderDocuments = $listDocuments.RootFolder.Subfolders.Add("$folderCountDocuments")
#$currentFolderListItems = $listListItems.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder)
#$currentFolderListItems["Title"] = $folderCountListItems
#$currentFolderListItems.Update();
$itemCountDocuments = 0
$itemCountListItems = 0
foreach ($row in $csv){
	
	$docNumber = $row.DocumentNumber
	$barIndex = $docNumber.IndexOf('-')
	$docNumberSuffixLen = $docNumber.Length - $barIndex -1
	$docFolderName = $docNumber.Substring($barIndex+1,$docNumberSuffixLen)
	
	#create folder $docFolderName is not exist
	
	$targetDocumentFolder = $web.GetFolder($listDocuments.RootFolder.ServerRelativeUrl + "/" + $docFolderName)

	Write-Host $docFolderName -ForegroundColor Yellow
	if(-not $targetDocumentFolder.Exists)
	{
		$targetDocumentFolder = $listDocuments.RootFolder.SubFolders.Add("$docFolderName")	
		Write-Host $targetDocumentFolder.Url "target document folder is created" -ForegroundColor Green
	}
	
	$targetListFolder = $web.GetFolder($listListItems.RootFolder.ServerRelativeUrl + "/" + $docFolderName)
	
	if(-not $targetListFolder.Exists)
	{
		$targetListFolder = $listListItems.AddItem("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder)
		$targetListFolder["Title"] = $docFolderName
		$targetListFolder.Update();
		Write-Host $targetListFolder.Url  "target list folder is created" -ForegroundColor Green
	}
	
	<#
	if($itemCountListItems%$folderCountLimitListItems -eq 0)
	{
		Write-host "Creating folder " $folderCountListItems
		$itemFolderUrl = "/invoices/" + $importYear + "/Lists/" + $listListItems
		$currentFolderListItems = $listListItems.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder)
		$currentFolderListItems["Title"] = $folderCountListItems
		$currentFolderListItems.Update();
		$folderCountListItems++
	}#>
	
	$fileName = $row.DocumentNumber + ".pdf"
	$filePath = $invoiceSourceFolder +  $fileName
	
	# Check if file exists
	$filePathAtDestination = "$targetDocumentFolder/$fileName"
	$fileExists = $web.GetFile($filePathAtDestination).Exists
	try
	{
		$fileStream = ([System.IO.FileInfo] (Get-Item $filePath)).OpenRead()
		
		# If file hasn't been added already, add it
		if(!$fileExists)
		{
			$spFile = $targetDocumentFolder.Files.Add($targetDocumentFolder.Url + "/" + $fileName, [System.IO.Stream] $fileStream, $false)
			$itemCountDocuments++
			Write-Host  $fileName " is added successful" -ForegroundColor Green
		}
		
		$itemFolderUrl = $targetListFolder.Url + "/"
		
		$item = $listListItems.AddItem($itemFolderUrl, [Microsoft.Sharepoint.SPFileSystemObjectType]::File, $row.DocumentNumber)
		$item[$documentType] = "Invoice"
		$item[$documentName] = $row.DocumentNumber
		$item["Title"] = $row.DocumentNumber
		
		$item[$invoiceGUID] = $row.InvoiceGUID
		$item[$invoiceType] = $row.InvoiceTypeCode
		$item[$customerNumber] = $row.CustomerNo
		$item[$customerName] = $row.CustomerName
		$item[$invoiceDate] = $row.InvoiceDate
		$item[$invoiceTotal] = $row.InvoiceTotal
		$item[$auctionID] = $row.AuctionID
		$item[$invoiceNumberSuffix] = $row.InvoiceNumberSuffix
		$item[$goodID] = $row.GoodNo
		$item[$plateNumber] = $row.PlateNo
		$item[$VIN] = $row.VIN
		$item[$consignmentVendorNumber] = $row.ConsignmentVendorNumber
		$item[$consignmentGoodNumber] = $row.ConsignmentGoodNumber
		
		$item[$goodGuid] = $row.GoodGUID
		
		$branchID = getBranchNameID -branchName $row.BranchName -branchCode $row.BranchCode
		
		$item[$branchName] = $branchID
		$documentUrl = New-Object Microsoft.SharePoint.SPFieldURLValue
		$documentUrl.Description = $fileName
		$documentUrl.URL = $web.Url + "/" + $targetDocumentFolder + "/" + $fileName
		
		$item[$documentLink] = $documentUrl
		$item.Update()
		$itemCountListItems++
		
	
	}
	catch
	{
		Write-Host "Error adding file: " $filePath"`n"$_ -foregroundcolor red
		break
	}
	
}
Write-Host "`n=================`nImport Completed.`nFiles Added: $itemCountDocuments.`nRows Added: $itemCountListItems.`n=================`n"


Remove-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue